package com.mdlib.droid.api.helper;

import android.text.TextUtils;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;
import com.mdlib.droid.AppContext;
import com.mdlib.droid.api.callback.JsonCallback;
import com.mdlib.droid.common.ConfigContant;
import com.mdlib.droid.common.OkHead;
import com.mdlib.droid.model.AccountModel;

import org.json.JSONObject;

import java.io.File;
import java.util.Map;


/**
 * Created by bin on 17/6/4.
 */

public class ApiHttpClient {


    public static void post(String partUrl, Map<String, String> params, JsonCallback callback,
                            Object tag, boolean isLogin) {
        JSONObject jsonObject = new JSONObject(params);
        OkGo.getInstance().addCommonHeaders(getHead(isLogin))
                .post(getAbsoulteApiUrl(partUrl))
                .tag(tag)
                .upJson(jsonObject)
                .execute(callback);
    }

    public static void post(String partUrl, JsonCallback callback,
                            Object tag, boolean isLogin) {
        OkGo.getInstance().addCommonHeaders(getHead(isLogin))
                .post(getAbsoulteApiUrl(partUrl))
                .tag(tag)
                .execute(callback);
    }

    private static HttpHeaders getHead(boolean isLogin) {
        if (isLogin) {
            return OkHead.getCommonHeadToken(AppContext.getInstance());
        } else {
            return OkHead.getCommonHead(AppContext.getInstance());
        }
    }

    public static void post(String partUrl, File imgs, JsonCallback callback,
                            Object tag, boolean isLogin) {
        OkGo.getInstance().addCommonHeaders(getHead(isLogin))
                .post(getAbsoulteApiUrl(partUrl))
                .tag(tag)
                .params("file", imgs)
                .execute(callback);
    }

    public static void get(String partUrl, StringCallback callback, Object tag) {
        OkGo.get(partUrl )
                .tag(tag)
                .execute(callback);
    }
    public static void get(String partUrl, FileCallback callback, Object tag) {
        OkGo.get(partUrl )
                .tag(tag)
                .execute(callback);
    }
    private static String getAbsoulteApiUrl(String partUrl) {
        String allUrl = ConfigContant.BASE_API + partUrl;
        if (AccountModel.getInstance().isLogin()) {
            if (!TextUtils.isEmpty(AppContext.getInstance().getSessionId())) {
                allUrl += "?session_id=" + AppContext.getInstance().getSessionId();
            }
        }
        return allUrl;
    }


}
